package exc;

import java.io.File;
import java.io.IOException;

import buffer.pager;

import data.Table.Table;
import data.meto.table;

public class DBlite {

	public static String  dbPath = "./source/";
	
	/**
	 * create db , if exists ,only print the warnings
	 * @param dbname
	 */
	public void Create(String dbname){
		
		String path = dbPath + dbname+".db";		
		File dbfile = new File(path);
		if(!dbfile.exists()){
			try {
				dbfile.createNewFile();
				Table tb = new Table(path,true);
				tb.ini();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			System.out.println("the DB: "+dbname+" is exists!!");
		}
	}
	
	public Table Open(String dbname){
		
		String path = dbPath + dbname+".db";
		File dbfile = new File(path);
		if(!dbfile.exists()){
			System.out.println("there is no db:"+dbname);
			return null;
		}else{
			Table tb = new Table(path);
			return tb;			
		}
	}
	
	public boolean Delete(String dbname){

		String path = dbPath + dbname+".db";
		File dbfile = new File(path);
		if(!dbfile.exists()){
			System.out.println("there is no db:"+dbname+" to delete");
			return false;
		}else {
			return dbfile.delete();
		}
	}
	
	public void Clear(String dbname){
		String path = dbPath + dbname+".db";
		File dbfile = new File(path);
		if(!dbfile.exists()){
			System.out.println("there is no db:"+dbname+" to clear");
		}else{
			Delete(dbname);
			Create(dbname);
		}
	}
	
	public pager Ini(String dbname){
		String path = dbPath + dbname+".db";
		pager pg = new pager(path);
		return pg;
	}
	
	public void CreateTable(pager page,String tbname,String ...args){
		
		if(page.Alltables.get(tbname)!=null){
			System.out.println("table :"+tbname+" is exits!!");
			return ;
		}		
		table tb = new table();
		tb.setTableName(tbname);
		tb.setTableNum(args.length);
//		tb.setRootPageNum(page.getFreePage().getnum);
		for(int i=0;i<args.length;i++){
			if(i%2==0){
				tb.elements.add(args[i]);
			}else{
				tb.types.add(args[i]);
			}
		}
		page.Alltables.put(tbname, tb);
	}
	
	
	
	
	
	
}
